package cn.zn.framework.handler;

import cn.zn.framework.bean.LoginUser;
import cn.zn.framework.utils.SecurityUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final Logger log = LoggerFactory.getLogger(MyMetaObjectHandler.class);

    /**
     * 插入
     *
     * @param metaObject metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            LoginUser theUser = SecurityUtil.getLoginUser();
            String userId = null;
            if (theUser != null) {
                userId = theUser.getUsername();
            }
            this.strictInsertFill(metaObject, "createBy", String.class, userId);
            this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
            this.strictInsertFill(metaObject, "modifyBy", String.class, userId);
            this.strictInsertFill(metaObject, "modifyTime", Date.class, new Date());
        } catch (Exception e) {
            log.error("获取用户失败:" + e.getMessage());
        }
    }

    /**
     * 更新
     *
     * @param metaObject metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            LoginUser theUser = SecurityUtil.getLoginUser();
            String userId = null;
            if (theUser != null) {
                userId = theUser.getUsername();
            }
            this.strictInsertFill(metaObject, "modifyBy", String.class, userId);
            this.strictInsertFill(metaObject, "modifyTime", Date.class, new Date());
        } catch (Exception e) {
            log.error("获取用户失败:" + e.getMessage());
        }
    }
}
